package com.example.easybuy.listen;

import com.example.easybuy.entity.OrderDetail;
import com.example.easybuy.entity.Product;
import com.example.easybuy.service.OrderService;
import com.example.easybuy.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class RedisListener implements MessageListener {
    @Autowired
    private OrderService orderService;
    @Autowired
    private ProductService productService;

    @Override
    public void onMessage(Message message, byte[] bytes) {
        String expiredKey = new String(message.getBody());//拿到过期的键
        System.out.println("过期了" + expiredKey);
        String orderId = expiredKey.substring(0, expiredKey.length() - 6);
        Map<String, Object> map = new HashMap<>();
        map.put("id", orderId);
        map.put("itStatus", 3);
        try {
            orderService.updateOrder(map);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        Map<String, Object> updateProductMap = new HashMap<>();
        updateProductMap.put("orderId", orderId);
        List<OrderDetail> list = orderService.selectOrderDetail(updateProductMap);
        Product product;
        Map<String, Object> map1;//获取商品对象 更改库存
        for (OrderDetail OrderDetail : list) {
            map1 = new HashMap<>();
            map1.put("id", OrderDetail.getProductId());
            product = productService.getPro(map1);
            map1.put("stock", product.getStock() + OrderDetail.getQuantity());
            map1.put("preStock", product.getPreStock() - OrderDetail.getQuantity());
            try {
                productService.updatePro(map1, null);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    }
}